﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Volo.Abp;

namespace mozhi.smarterp.Finance.Finances
{
    /// <summary>
    /// 期末处理项
    /// </summary>
    public class EndPeriodProcessItem : AggregateRootBase<Guid>
    {
        public string Name { private set; get; }

        public int Index { private set; get; }

        public List<EndPeriodProcessItemSetting> Settings { private set; get; }

        private EndPeriodProcessItem() { }

        public EndPeriodProcessItem(Guid id , string name, int index)
        {
            Id = id;
            Name = name;
            Index = index;
            Settings = new List<EndPeriodProcessItemSetting>();

            Validate();
        }


        public void AddSettings(List<EndPeriodProcessItemSetting> settings)
        {
            if (settings == null)
                throw new ArgumentNullException(nameof(settings));

            foreach (var setting in settings)
            {
                var match = Settings.FirstOrDefault(x => x.Id == setting.Id || x.DefaultAccountCode == setting.DefaultAccountCode);

                if (match != null)
                    match.ChangeCustomAccountCode(setting.DefaultAccountCode);
                else
                    Settings.Add(setting);
            }
        }
        

        private void Validate()
        {
            if(Name.IsNullOrEmpty())
                throw new UserFriendlyException("名称不能为空", "100000");

            if (Index <= 0)
                throw new UserFriendlyException("序号不能为空", "100000");
        }
    }

    public class EndPeriodProcessItemSetting : EntityBase<Guid>
    {
        public Guid EndPeriodProcessItemId { private set; get; }

        public string Name { private set; get; }

        public string DefaultAccountCode { private set; get; }

        public string CustomAccountCode { private set; get; }

        public int Index { private set; get; }

        private EndPeriodProcessItemSetting() { }

        public EndPeriodProcessItemSetting(Guid id , Guid parentId , string name, string defaultAccountCode, string customAccountCode , int index)
        {
            Name = name;
            DefaultAccountCode = defaultAccountCode;
            CustomAccountCode = customAccountCode;
            Id = id;
            EndPeriodProcessItemId = parentId;
            Index = index;

            Validate();
        }

        public void ChangeCustomAccountCode(string customAccountCode)
        {
            CustomAccountCode = customAccountCode;
        }

        private void Validate()
        {
            if (Name.IsNullOrEmpty())
                throw new UserFriendlyException("名称不能为空", "100000");

            if (DefaultAccountCode.IsNullOrEmpty())
                throw new UserFriendlyException("名称不能为空", "100000");

            if(EndPeriodProcessItemId==default)
                throw new UserFriendlyException("期末处理项Id不能为空", "100000");
        }
    }
}
